import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入组件
import login from '../components/login.vue'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome.vue'
import Users from '../components/user/Users.vue'

Vue.use(VueRouter)

const routes = [

  //  监听/ 路径，，重定向到/login
  {
    path: "/", redirect: "/login"
  },

  // 为组件login配置访问路径
  {
    path: '/login', component: login
  },
  {
    path: '/home',
    component: Home,
    redirect:'/welcome',
    children: [
      { path: '/welcome', component: Welcome },
    // 路径/users 是服务器（后台）规定的，不能修改
      { path:'/users',component:Users }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 挂载路由导航守卫 ---控制访问权限
router.beforeEach((to, from, next) => {

  // to将要访问的路径
  // from 代表从哪个路径跳转而来
  // next 是一个函数，表示放行

  if (to.path === '/login') return next(); // 放行
  const tokenStr = window.sessionStorage.getItem('token')
  if (!tokenStr) return next('/login')
  next()

})
export default router
